import 'dart:collection';
import 'dart:io';
import 'dart:convert';
import 'dart:async';

/// 需要哪些自定义配置项
/// port端口号
/// web目录
/// ws的最大连接数限制
/// 是否开启连接日志
///

class ClientInfo{

}

final Map<int,WebSocket> wsClients = HashMap();
void main() async {
  final server = await HttpServer.bind(InternetAddress.anyIPv4, 3000);
  print('WebSocket 和 HTTP 静态资源服务器已启动: http://localhost:3000');

  await for (HttpRequest request in server) {
    // 处理 WebSocket 升级请求
    if (WebSocketTransformer.isUpgradeRequest(request)) {
      final webSocket = await WebSocketTransformer.upgrade(request);
      final addr = request.connectionInfo!.remotePort;
      if (!wsClients.containsKey(addr)){
        wsClients[addr] = webSocket;
      }
      print('WebSocket 客户端{$addr}已连接');
      // 监听 WebSocket 消息
      webSocket.listen((message) {
        print('服务器收到 WebSocket 消息: $message');
        // wsClients.values.forEach((ws)=>ws.add("$addr:$message"));
        // 使用stream流过滤当前用户
        Stream.fromIterable(wsClients.values).where((v)=>v != wsClients[addr]).forEach((ws)=>ws.add("$addr:$message"));
      }, onDone: () {
        wsClients.remove(addr);
        print('客户端${{addr}}已断开连接');
      });
    } else {
      // 处理 HTTP 请求，返回静态资源
      await handleHttpRequest(request);
    }
  }
}


// 处理 HTTP 请求并返回静态资源
Future<void> handleHttpRequest(HttpRequest request) async {
  final filePath = 'web${request.uri.path}';

  // 默认返回 index.html
  if (request.uri.path == '/') {
    final file = File('web/index.html');
    if (await file.exists()) {
      request.response.headers.contentType = ContentType.html;
      await request.response.addStream(file.openRead());
    } else {
      request.response.statusCode = HttpStatus.notFound;
      request.response.write('404 Not Found');
    }
  } else {
    final file = File(filePath);
    if (await file.exists()) {
      // 自动检测文件类型
      final fileExtension = file.uri.pathSegments.last.split('.').last;
      request.response.headers.contentType = _getContentType(fileExtension);
      await request.response.addStream(file.openRead());
    } else {
      request.response.statusCode = HttpStatus.notFound;
      request.response.write('404 Not Found');
    }
  }
  await request.response.close();
}

// 根据文件扩展名获取对应的 ContentType
ContentType _getContentType(String extension) {
  switch (extension.toLowerCase()) {
    case 'html':
      return ContentType.html;
    case 'json':
      return ContentType.json;
    case 'txt':
      return ContentType.text;
    case 'css':
      return ContentType('text', 'css');
    case 'js':
      return ContentType('application', 'javascript');
    case 'jpg':
    case 'jpeg':
      return ContentType('image', 'jpeg');
    case 'png':
      return ContentType('image', 'png');
    case 'gif':
      return ContentType('image', 'gif');
    case 'svg':
      return ContentType('image', 'svg+xml');
    case 'ico':
      return ContentType('image', 'x-icon');
    case 'pdf':
      return ContentType('application', 'pdf');
    case 'zip':
      return ContentType('application', 'zip');
    default:
      return ContentType.binary; // Default to binary for unknown types
  }
}

